package com.web.filter;

import com.util.SessionUtils;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginFilter implements Filter {

    /**
     * 只执行一次，第一次请求时执行
     * @param filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig){
        // nothing
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

                throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;

        HttpServletResponse resp = (HttpServletResponse) response;

        // 如果需要校验,判断用户是否登录,是,则放行,反之回到登录页面
        if (!SessionUtils.hasUserSession(req.getSession(false))) {
            resp.sendRedirect("/login");
            return;
        }
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        // nothing
    }
}